﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.ComponentModel;

namespace Kiosk
{
    /// <summary>
    /// Interaction logic for PasswordPrompt.xaml
    /// </summary>
    public partial class PasswordPrompt : Window
    {

        [DllImport("user32.dll")]
        static extern bool HideCaret(IntPtr hWnd); //for caret hiding in makeshift password box
        OnScreenKeyboard theKeyboard = new OnScreenKeyboard();
        System.Windows.Forms.MaskedTextBox txtPassword;
        private string additionalComments;

        public Window previousWindow { get; set; }

        public PasswordPrompt()
        {
            InitializeComponent();

            MainGrid.Children.Add(theKeyboard);
            Grid.SetRow(theKeyboard, 2);
            Grid.SetColumn(theKeyboard, 0);
            Grid.SetColumnSpan(theKeyboard, 3);
            theKeyboard.VerticalAlignment = VerticalAlignment.Bottom;
            additionalComments = "";       
        }//end constructor PasswordPrompt

        public PasswordPrompt(string comments)
        {
            InitializeComponent();

            MainGrid.Children.Add(theKeyboard);
            Grid.SetRow(theKeyboard, 2);
            Grid.SetColumn(theKeyboard, 0);
            Grid.SetColumnSpan(theKeyboard, 3);
            theKeyboard.VerticalAlignment = VerticalAlignment.Bottom; 
            additionalComments = comments;
        }

        /// <summary>
        /// This method clears the password box and returns user to the previous page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {            
            previousWindow.Show();
            this.Close();            
        }//end method btnCancel_Click


        /// <summary>
        /// This method is called when the Submit button is clicked. It checks to see if the 
        /// password field has text. If it does then it then checks for SQL injection.
        /// If it passes all of this it will then check the credentials against the database.
        /// If the credentials are correct, the email is sent.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            //Check for an empty password 
            if (txtPassword.Text == String.Empty || txtPassword.Text == null)
            {
                txtErrorMessage.Text = "The PASSWORD can not be blank.";
            }
            //Check the credentials against the database
            else
            {
                if (sGlobals.isValidPassword(sGlobals.currentUsername, txtPassword.Text))
                {
                    sendEmail();
                    string logStatement = "INSERT INTO lgd_mentor_student_actions (mentor_id, student_id, " + 
                                    "date_time, action_performed_id) VALUES ('" + sGlobals.selectedMentorID + "' , (SELECT user_id FROM users " + 
                                    "WHERE username = '" + sGlobals.currentUsername + "'), NOW(), 'E')";

                    sGlobals.dbWrapper.ExecuteNonQuery(logStatement);
                    sGlobals.mentorDisplay.previousPage.Show();
                    foreach (Window win in Application.Current.Windows)
                    {
                        if ((string)win.Tag == "comments")
                        {
                            win.Close();
                        }
                    }
                    this.Close();
                }
                else
                {
                    txtErrorMessage.Text = "The PASSWORD is not valid";
                }
            }
        }//end method btnSubmit_click

        private void focusHandler(object sender, RoutedEventArgs e)
        {
            if (sender is PasswordBox) //show keyboard and bind
            {
                theKeyboard.bindToControl((TextBox)sender);
                theKeyboard.show();
            }
            else if (sender is OnScreenKeyboard) // special do nothing case...focus is getting bounced around between the keyboard and bound control
            {

            }
            else //hide keyboard (clicked button or window or something)
            {
                theKeyboard.clearControlBinding();
                theKeyboard.hide();
            }
        }

        private void windowLeftMouseButtonUp(object sender, MouseButtonEventArgs e)
        {
            theKeyboard.clearControlBinding();
            theKeyboard.hide();
            btnSubmit.Focus();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtPassword = new System.Windows.Forms.MaskedTextBox();
            txtPassword.Dock = System.Windows.Forms.DockStyle.Fill;
            txtPassword.Font = new System.Drawing.Font("Sequoe UI", 18);
            txtPassword.PasswordChar = '*';

            //txtPassword.Click += new EventHandler(MaskedTextBox_GotFocus); //so cursor gets hidden on click
            txtPassword.GotFocus += new EventHandler(MaskedTextBox_GotFocus);
            wfHost.Child = txtPassword;
            txtPassword.Focus();
        }

        private void MaskedTextBox_GotFocus(object sender, EventArgs e)
        {
            HideCaret(txtPassword.Handle);
            theKeyboard.bindToControl(sender);
            theKeyboard.show();
        }

        private void sendEmail()
        {
            sGlobals.sendingEmail = true; 
            string mentorEmailQuery = "SELECT email FROM mentor WHERE mentor_id = '" + sGlobals.selectedMentorID + "'";
            string kioskEmailQuery = "SELECT setting_value FROM settings WHERE setting_name = 'EMAIL ADDRESS'";
            MailAddress from = new MailAddress(sGlobals.dbWrapper.ExecuteScalarSQL(kioskEmailQuery));
            MailAddress to = new MailAddress(sGlobals.dbWrapper.ExecuteScalarSQL(mentorEmailQuery));
            MailMessage message = new MailMessage(from, to);
            message.Subject = "Clearfield Career Kiosk";
            message.Body = sGlobals.contactMentor.emailText + additionalComments;
            sGlobals.smtpClient.SendCompleted += new SendCompletedEventHandler(sendCompleted);
            MessageBox sendingMessage = new MessageBox("Please wait while your email is being sent", "sending");                
            sGlobals.smtpClient.SendAsync(message, "token");
            sendingMessage.ShowDialog();                            
        }

        private void sendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            foreach (Window win in Application.Current.Windows)
            {
                if ((string)win.Tag == "sending")
                {
                    win.Close();
                }
            }
            if (e.Error != null)
            {
                WarningMessage warn = new WarningMessage();
                warn.lblMessage.Content = "There was a problem sending the email. Please try again later.\r\nIf the problem continues, please contact your system administrator.";
                warn.ShowDialog();
                Console.WriteLine("\n***************************************");
                Console.WriteLine(e.Error.Message);
                Console.WriteLine("**************************************\n");
            }
            sGlobals.sendingEmail = false;
        }
    }//end partial class PasswordPrompt : Window
}//end namespace Kiosk
